package com.init.iblog.service.impl;

import com.init.iblog.domain.ResponseResult;
import com.init.iblog.domain.entity.LoginUser;
import com.init.iblog.domain.entity.User;
import com.init.iblog.domain.vo.UserInfoVo;
import com.init.iblog.domain.vo.UserLoginVo;
import com.init.iblog.service.AdminLoginService;
import com.init.iblog.service.LoginService;
import com.init.iblog.utils.BeanCopyUtils;
import com.init.iblog.utils.JwtUtil;
import com.init.iblog.utils.RedisCache;
import com.init.iblog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 后端登录
 */
@Service
public class AdminLoginServiceImpl implements AdminLoginService {

    /**
     * 默认情况下容器中没有，需要自己创建并注入到容器中
     * 通过iblog_front子模块下的config配置中的SecuityConfig配置将其注入到容器中
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public ResponseResult userLogin(User user) {
        //用户认证：传入用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getName(),user.getPassword());
        /**
         * authenticationManager最终会调用UserDetailsServiceImpl内的方法，去数据库内进行查询验证用户信息并返回
         */
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //获取userid 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //用户id是long类型，将其转化为String类型
        String userId = loginUser.getUser().getId().toString();
        //createJWT(）方法传入一个String后会加密生成一个token
        String jwt = JwtUtil.createJWT(userId);

        //把用户信息存入redis(需要配置redis)
        redisCache.setCacheObject("login" + userId,loginUser);

        //把token封装返回即可
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        System.out.println("=================token+" + jwt);
        return ResponseResult.okResult(map);
    }

    /**
     * 退出登录
     * @return
     */
    @Override
    public ResponseResult logout() {

        //获取当前登录用户id
        Long userId = SecurityUtils.getUserId();
        //删除redis中对应的值
        redisCache.deleteObject("login"+userId);
        return ResponseResult.okResult();
    }
}
